<?php

namespace Channel\Service;
use Common\Libiary\LogEX;

/**
 * Created by PhpStorm.
 * User: lixiangyang
 * Date: 16/9/8
 * Time: 下午5:16
 */
class ShortLinkService
{
    /**
     * 分页获取短连接
     * @param $page
     * @return mixed
     */
    public static function getShortUrlList($page = 1, $pagesize = 20) {

        $list = M('ShortLink')
            ->field(['id', 'title', 'url_short', 'url_long', 'created_at'])
            ->order('id desc')
            ->page($page, $pagesize)
            ->select();
        foreach($list as $k=>$v) {
            $list[$k]['showid'] = self::genShowId($v['created_at'], $v['id']);
        }
        $count = M('ShortLink')
                    ->count();
        return [
            'count' => $count,
            'list' => $list
        ];
    }

    /**
     *  呈现id生成方式年月日+主键id(不足三位补0)
     * @param $created_date
     * @param $id
     * @return string
     */
    private static function genShowId($created_date, $id) {
        return sprintf('%s%03d', date('Ymd', strtotime($created_date)), $id);
    }

    /**
     * 根据主键查询短连接
     * @param $id
     * @return mixed
     */
    public static function getShortLinkDetail($id) {
        return M('ShortLink')
                ->where(['id'=>$id])
                ->find();
    }

    /**
     * @param $params
     * @return mixed
     */
    public static function findshortLink($params) {
        return M('ShortLink')
                ->field(['id', 'title', 'url_short', 'url_long', 'created_at'])
                ->where($params)->find();
    }

    /**
     * 保存短链接
     * @param $title
     * @param $longUrl
     * @return array
     */
    public static function save($title, $longUrl) {
        try {
            $info = ShortLinkService::findshortLink([
                'url_long' => $longUrl
            ]);
            if($info) {
                return [
                    'status' => 10001,
                    'msg' => '该链接已经存在',
                    'data' => $info
                ];
            }
            $gateUrl = TP_DEBUG ? "http://m.9now.net/index/gate" : "http://m.mwee.cn/index/gate";
            $_longUrl = sprintf("%s?title=%s&gourl=%s", $gateUrl, urlencode($title), urlencode($longUrl));
            $shortUrlInfo = ShortLinkService::getUrl($_longUrl);
            $info = [
                'title' => $title,
                'url_short' => $shortUrlInfo['result']['url_short'],
                'url_long' => $longUrl,
                'created_at' => date('Y-m-d H:i:s')
            ];
            LogEX::i('保存短连接', ['data'=> $info, 'shortUrlInfo'=>$shortUrlInfo],__FILE__,__LINE__);
            M('ShortLink')->add($info);
            $shortUrlInfo['result']['newId'] = M('ShortLink')->getLastInsID();
            return [
                'status' => 0,
                'data' => $shortUrlInfo['result']
            ];

        } catch(\Exception $e) {
            LogEX::i('保存短连接异常', ['data'=> $e],__FILE__,__LINE__);
            return [
                'ret' => $e->getCode(),
                'msg' => $e->getMessage()
            ];
        }
    }

    /**
     * 生成短链接
     * @param $longUrl
     * @return mixed
     * @throws \Exception
     */
    public static function getUrl($longUrl)
    {
        $urlRes = json_encode([
            'appid' => 300,
            'url' => $longUrl
        ]);
        $serviceURl = TP_DEBUG ? 'http://s.9now.net/admin/short/url' : 'http://s.mwee.cn/admin/short/url';
        $raw = self::postJson($serviceURl, $urlRes);
        $ret = json_decode($raw, true);

        LogEX::i('短连接服务', ['data'=> $raw, 'params' => $urlRes,'serviceURl' => $serviceURl, 'tp_debug' =>TP_DEBUG],__FILE__,__LINE__);


        if($ret && $ret['statusCode'] == 200) {
            return $ret;
        }
        throw new \Exception("调用短连接服务失败", 1000);
    }

    private static function postJson($url, $data)
    {
        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_USERAGENT => 'Mozilla/5.0 PHP CURL',
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => $data
        ));
        $ret = curl_exec($ch);
        LogEX::i('短连接curl', ['data'=> curl_getinfo($ch)],__FILE__,__LINE__);
        curl_close($ch);
        return $ret;
    }

}